<script>
import {
  getEnterpriseListAPI,
  delEnterpriseAPI,
  getRentBuildingAPI,
  addRentAPI,
  getEnterpriseRentListAPI,
  rentingOutAPI,
  delRentAPI,
} from "@/api/enterprise.js";
import { upLoadFile } from "@/api/common.js";
import {mapState} from 'vuex'
export default {
  data() {
    return {
      params: {
        name: "",
        page: 1,
        pageSize: 2,
      },
      list: [], //列表数据
      total: 0,
      rentDialogVisible: false, //控制弹窗显示隐藏
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: "", // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [], // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "change" },
        ],
        rentTime: [
          { required: true, message: "请选择租赁日期", trigger: "change" },
        ],
        contractId: [
          { required: true, message: "请上传合同文件", trigger: "change" },
        ],
      },
      rentBuildingList: [],
    };
  },
  methods: {
    async getEnterpriseList() {
      //获取企业列表
      const res = await getEnterpriseListAPI(this.params);
      console.log(res, "getEnterpriseListAPI");
      this.list = res.data.rows.map((item) => {
        return {
          ...item,
          rentList: [],
        };
      });
      this.total = res.data.total;
    },
    handleChange(val) {
      //切换页码
      this.params.page = val;
      this.getEnterpriseList();
    },
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1;
    },
    search() {
      //点击查询
      this.params.page = 1;
      this.getEnterpriseList();
    },
    toEditPage(id) {
      this.$router.push({
        path: "/addEnterprise",
        query: { id },
      });
    },
    delEnterprise(id) {
      this.$confirm("此操作将永久删除该企业吗？", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (this.params.page > 1 && this.list.length == 1) {
            this.params.page--;
          }
          await delEnterpriseAPI(id);
          this.getEnterpriseList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    closeDialog() {
      //控制弹窗关闭
      this.rentDialogVisible = false;
      //清空数据 只能清空绑定prop表单域的数据  清空校验提示
      this.$refs.addForm.resetFilelds();
      //清空所有数据
      this.rentForm = {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: "", // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [], // 合同时间
      };
      //清空upload上传数据
      this.$refs.upload.clearFiles();
    },
    addRent(id) {
      //显示弹窗
      this.rentDialogVisible = true;
      this.getRentBuildingList();
      this.rentForm.enterpriseId = id;
    },
    async getRentBuildingList() {
      //查询可租赁楼宇信息列表
      const res = await getRentBuildingAPI();
      // console.log(res,'getBuildList')
      this.rentBuildingList = res.data;
    },
    async httpRequest({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", 2);
      const res = await upLoadFile(formData);
      // console.log(res,'upload')
      this.rentForm.contractId = res.data.id;
      this.rentForm.contractUrl = res.data.url;
      //非常规表单校验，需要单独校验，隐藏提示语
      this.$refs.addForm.validateField('contractId');
    },
    beforeUpload(file) {
      const fileType = [
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/msword",
        "application/pdf",
      ];
      if (!fileType.includes(file.type)) {
        this.message.warning("上传文件类型错误");
        return false;
      }
      if (file.size / 1024 / 1024 > 5) {
        this.message.error("上传文件大小超过5M");
        return false;
      }
    },
    onExceed() {
      this.message.warning("文件超出上传限制");
    },
    confirmAdd() {
      //添加租赁合同
      this.$refs.addForm.validate(async (flag) => {
        //兜底校验
        if (!flag) return;
        //提交接口  添加租赁合同
        const [startTime, endTime] = this.rentForm.rentTime;
        this.rentForm.startTime = startTime + '';
        this.rentForm.endTime = endTime + '';
        console.log(startTime, endTime, "启示日期");
        delete this.rentForm.rentTime;
        const res = await addRentAPI(this.rentForm);
        console.log(res, "addRent");
        this.$message.success("添加合同成功");
        this.getEnterpriseList();
        this.closeDialog(); //关闭弹框 清空数据
      });
    },
    onRemove() {
      //移除了文件
      this.rentForm.contractId = "";
      this.rentForm.contractUrl = "";
      this.$refs.addForm.validateField("contractId");
    },
    async expandChange(row, expandRows) {
      //表格展开关闭都出发 第一个参数当前点击行 第二个参数展开数据的数组
      //判断是否为展开
      const isInclude = expandRows.find((item) => item.id == row.id);
      if (isInclude) {
        const res = await getEnterpriseRentListAPI(row.id);
        // console.log(res,'getEnterpriseRentList')
        row.rentList = res.data;
      }
    },
    formatStatus(status) {
      //格式化合同类型
      const Map = {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      };
      return Map[status];
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: "warning",
        1: "success",
        2: "info",
        3: "danger",
      };
      // return 格式化之后的中文显示
      return MAP[status];
    },
    rentingOut(id){//退租
      this.$confirm("您确定要退租吗？", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
            await rentingOutAPI(id);
            this.getEnterpriseList(); 
            this.$message({
            type: "success",
            message: "退租成功!",
          })
        })
        .catch(() => {});
    },
    async delRent(id){//删除退租的数据
      this.$confirm("您确定要删除此条数据吗？", "温馨提示")
        .then(async () => {
            await delRentAPI(id)
            this.getEnterpriseList(); 
            this.$message({
            type: "success",
            message: "删除信息成功!",
          })
        })
        .catch(() => {});
    }
  },
  created() {
    this.getEnterpriseList();
  },
  computed:{
    ...mapState('menu',[Permission])
  }
};
</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        @clear="search"
        class="search-main"
        v-model="params.name"
      />
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addEnterprise')"
       v-if="permission.includes('park:enterprise:add_edit')" >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="expandChange">
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime">
                <template #default="rentObj">
                  {{ rentObj.row.startTime }}至{{ rentObj.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="rentObj">
                  <el-tag :type="formatInfoType(rentObj.row.status)">
                    {{ formatStatus(rentObj.row.status) }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="rentObj">
                  <el-button size="mini" :disabled="rentObj.row.status==3" type="text" @click="rentingOut(rentObj.row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="rentObj.row.status!==3" @click="delRent(rentObj.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)"
              >添加合同</el-button
            >
            <el-button size="mini" type="text" @click="$router.push(`/enterpriseDetail/${scope.row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="toEditPage(scope.row.id)"
            v-permission="'park:enterprise:remove'"  
            >编辑</el-button
            >
            <!-- 添加按钮权限 v-if="permission.includes('park:enterprise:remove')"-->
            <el-button
              size="mini"
              type="text"
              @click="delEnterprise(scope.row.id)"
              v-if="permission.includes('park:enterprise:remove')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <!--total   pageSize  @current-change是必须配置的 @current-page-->
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :pageSize="params.pageSize"
        @current-change="handleChange"
      />
    </div>
    <!-- 添加合同弹窗 -->
    <!--close-on-click-modal 点击遮罩层 不关闭弹窗-->
    <!--limit 允许上传最大数量  on-exceed 超出限制是执行 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
      :close-on-click-modal="false"
      :limit="1"
      :on-exceed="onExceed"
    >
      <!-- 表单区域 -->
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentBuildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <!-- on-remove 文件移除时自动执行 -->
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              action="#"
              :http-request="httpRequest"
              :before-upload="beforeUpload"
              :on-remove="onRemove"
              ref="upload"
            >
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
